<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2021/4/12
 * Time: 16:17
 * 信号模型
 */
namespace Io\Signal; // 这是等会自个要写的服务
class Worker
{
    // 接收
    public $onReceive = null;
    // 链接
    public $onConnect = null;

    public $onClose   = null;

    public $socket    = null;

    protected $sockets = [];

    public function __construct($socket_address)
    {
        $this->socket = stream_socket_server($socket_address);

//        $this->sockets[(int)$this->socket] = $this->socket;
//
//        stream_set_blocking($this->socket, 0);

        echo $socket_address.PHP_EOL;
    }

    public function accept()
    {
        while (true) {
            $this->debug("accept start");

            $client = @stream_socket_accept($this->socket);

            // 监听的过程是阻塞的
            pcntl_signal(SIGIO, $this->sigHander($client));
            posix_kill(posix_getpid(), SIGIO);

            // 分发
            pcntl_signal_dispatch();
            $this->debug("accept end");
             //处理完成之后关闭连接
             // 心跳检测 - 自己的心跳
             // fclose($client);
        }
    }

    public function sigHander($client)
    {
        return function($sig) use ($client){
            // is_callable判断一个参数是不是闭包
            if (is_callable($this->onConnect)) {
                ($this->onConnect)($this, $client);
            }
            $data = fread($client, 65535);
            if (is_callable($this->onReceive)) {
                ($this->onReceive)($this, $client, $data);
            }
        };
    }

    public function start()
    {
        // 启动服务
        $this->accept();
    }

    public function send($conn, $data)
    {
        $response = "HTTP/1.1 200 OK\r\n";
        $response .= "Content-Type: text/html;charset=UTF-8\r\n";
        $response .= "Connection: keep-alive\r\n";
        $response .= "Content-length: ".strlen($data)."\r\n\r\n";
        $response .= $data;

        fwrite($conn, $response);
    }

    public function debug($data, $flag = false)
    {
        if ($flag) {
            var_dump($data);
        } else {
            echo "==== >>>> : ".$data." \n";
        }
    }
}